package com.thientan.controller

import grails.converters.JSON

import com.thientan.model.ChiTietThuChi
import com.thientan.model.HopDong
import com.thientan.model.NhanVien
import com.thientan.model.enums.LoaiChiTietThuChi
import com.thientan.model.enums.LoaiNhanVien
import com.thientan.model.enums.TrangThaiHopDong
import com.thientan.service.ThuNganService
import com.thientan.utils.Constants
import com.thientan.utils.Utility

class ThuNganController extends NhanVienController{
	ThuNganService thuNganService

	@Override
	public String getDomainName() {
		message(code : "default.thientan.messages.thuNgan")
	}

	@Override
	public Object getDomainService() {
		return thuNganService
	}

	def initData = {
		List<NhanVien> thuNgans = NhanVien.findAllByLoaiNhanVien(LoaiNhanVien.THU_NGAN)
		Map result = ["thuNgan" : extractPropertiesAsMaps(thuNgans, ["id", "maNv"])]
		render result as JSON
	}

	private void putDataToMap(Map map, def cttc) {
		Double soTien = cttc[2] == LoaiChiTietThuChi.TRA_GOP ? cttc[1] : -cttc[1]
		if(map.get(cttc[0])){
			Double tienDaThu = map.get(cttc[0])
			tienDaThu += soTien
			map.put(cttc[0], tienDaThu)
		} else {
			map.put(cttc[0], soTien)
		}
	}
	
	protected Map buildExportData (Map exportParams) {
		Long thuNganId = Long.valueOf(params["nvThuNgan-id"])
		NhanVien thuNgan = NhanVien.get(thuNganId)
		String ngayXuat = new java.text.SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(new Date())
		int numHd = HopDong.countByNvThuNganAndTrangThaiNotEqual(thuNgan, TrangThaiHopDong.DONG)
		List<ChiTietThuChi> cttcs = ChiTietThuChi.withCriteria {
			createAlias("hopDong", "hd")
			projections {
				property("hd.id")
				property("soTien")
				property("loaiChiTiet")
				property("quyetToan")
			}
			eq("nhanVien", thuNgan)
			eq("hd.nvThuNgan.id", thuNgan.id)
			'in'("loaiChiTiet", [
				LoaiChiTietThuChi.TRA_GOP,
				LoaiChiTietThuChi.TRA_KHACH
			])
		}

		if (!cttcs && numHd == 0) {
			return ["data" : null,
				"tenThuNgan" : thuNgan.hoTen,
				"ngayXuat" : ngayXuat,
				"tongSoHd" : "0",
				"tongTienQuyetToan" : "0"]
		} else {
			Map hd2TienDaThu = [:]
			Map hd2TienDaThuChuaQt = [:]
			cttcs.each {
				putDataToMap(hd2TienDaThu, it)
				if(!it[3]) {
					putDataToMap(hd2TienDaThuChuaQt, it)
				}
			}

			List<HopDong> hds = HopDong.findAllByNvThuNganAndTrangThaiNotEqual(thuNgan, TrangThaiHopDong.DONG)
			List hdDataMap = extractPropertiesAsMapsWithOrderNumber(hds, [
				"id",
				"maHd",
				"trangThaiText",
				"giaTri",
				"tienDaThu",
				"tienConLai",
				"tienGiamGia"
			], true)

			hdDataMap = hdDataMap.collect{
				Map additionalMap = [
							"tienThuNganThu" : hd2TienDaThu.isEmpty() ? "0" : (hd2TienDaThu.get(it["id"]) ? Utility.moneyFormat(hd2TienDaThu.get(it["id"])) : "0"),
							"tienCanQuyetToan" : hd2TienDaThuChuaQt.isEmpty() ? "0" : (hd2TienDaThuChuaQt.get(it["id"]) ? Utility.moneyFormat(hd2TienDaThuChuaQt.get(it["id"])) : "0")]
				it + additionalMap
			}

			//TODO [HCD] Temporary ignore GhiChu column
			return ["data" : hdDataMap,
				"tenThuNgan" : thuNgan.hoTen,
				"ngayXuat" : ngayXuat,
				"tongSoHd" : hds.size().toString(),
				"tongTienQuyetToan" : hd2TienDaThuChuaQt.isEmpty() ? "0" : Utility.moneyFormat(hd2TienDaThuChuaQt.values().sum())]
		}
	}

	def quyetToan = {
		Map result = [:]
		try {
			NhanVien tn = NhanVien.get(Long.valueOf(params["thuNganId"]))
			List ct = ChiTietThuChi.withCriteria {
				createAlias("hopDong", "hd")
				projections {
					property("id")
					property("soTien")
					property("loaiChiTiet")
				}
				eq("quyetToan", false)
				eq("nhanVien", tn)
				eq("hd.nvThuNgan.id", tn.id)
				'in'("loaiChiTiet", [
					LoaiChiTietThuChi.TRA_GOP,
					LoaiChiTietThuChi.TRA_KHACH
				])
			}

			if (!ct) {
				String msg = message(code : "default.thientan.messages.noNeedQuyetToanThuNgan", args : [tn.hoTen])
				result = getFormMessage(true, "info", msg, null)
			} else {
				List ctIds = ct.collect {it[0]}
				ChiTietThuChi.executeUpdate("update ChiTietThuChi ct set ct.quyetToan = true where ct.id in (:ids)", [ids : ctIds])
				Double soTien = 0
				ct.each {
					if (it[2] == LoaiChiTietThuChi.TRA_GOP) {
						soTien += it[1]
					} else {
						soTien -= it[1]
					}
				}
				String msg = message(code : "default.thientan.messages.quyetToanThuNganSuccess", args : [soTien, tn.hoTen])
				result = getFormMessage(true, "info", msg, null)
			}
		} catch (Exception e) {
			log.error("Error occurred when settling for casher", e)
			String msg = message(code : "default.thientan.messages.quyetToanThuNganFailed", args : null)
			result = getFormMessage(true, "error", msg, null)
		}
		render result as JSON
	}
	
	@Override
	protected String getExportFileName() {
		"CongSoThuNgan"
	}
}
